import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000
})

request.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }

    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

request.interceptors.response.use(
  (res) => {
    // 如果返回数据是 blob，直接返回
    if (res.data instanceof Blob) return res.data

    const { data, message, success } = res.data

    if (success) {
      return data
    } else {
      Message({
        type: 'error',
        message: message
      })

      return Promise.reject(new Error(message))
    }
  },
  async(err) => {
    // token 超时 | 失效
    if (err.response.status === 401) {
      // 退出登录
      await store.dispatch('user/logout', { type: 'warning', message: '身份验证超时了，需要重新登录' })
      return Promise.reject(err)
    }

    Message({
      type: 'error',
      message: err.message
    })

    return Promise.reject(err)
  }
)

export default request
